package com.shz.config;


import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Random;

@Resource
@Component
public class MyPasswordEncoder implements PasswordEncoder {
    public static final Integer saltByte = 20;
//    @Resource

    @Override
    public String encode(CharSequence rawPassword) {

        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        System.out.println(str.length());
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        String rawstr = rawPassword.toString();
        sb.append(rawstr);
        StringBuilder pwd = new StringBuilder();
        for (int i = 0; i < saltByte; i++) {
            int number = random.nextInt(62);
            char c = str.charAt(number);
            pwd.append(c);
            sb.append(c);
        }
        return DigestUtils.md5DigestAsHex(sb.toString().getBytes())+pwd;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
//        String base64Hash=Base64.getEncoder().encodeToString(hash);

        String salt = encodedPassword.substring(encodedPassword.length() - saltByte);
        String needPwd = rawPassword.toString() + salt;
        return encodedPassword.equals(DigestUtils.md5DigestAsHex(needPwd.getBytes())+salt);
    }
}
